
from google.appengine.ext.webapp import template

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

from google.appengine.ext import db

import urllib
#from google.appengine.api import urlfetch
#import datetime
import re,os #cgi
import datastore
import library

from google.appengine.api import users

#from google.appengine.dist import use_library
#use_library('django','1.2')


# How to do a search using List ( cant use __key__ for list )
# li = "('Drop','Social')"
# q='select * from Membership where facility=72 and interest in ' + li + " order by last desc"
# t = db.GqlQuery( q )
# print t.count()
# for e in t :
#  print e.first,e.last,e.interest
  
# How to use db.Query to order,filter, etc.
#query = db.Query(datastore.Membership)
#query.filter("facility = ",72)   #3483
#query.order("gender").order("last").order("last")
#query.filter("interest in ",["Drop",])
#results = query.fetch(limit=50)
#for e in results:
#    print e.facility,e.first,e.last,e.interest

class Member:
   first = ""
   last  = ""
   email = ""
   resident = ""
   rating   = ""
   year     = ""

class Display(webapp.RequestHandler):

    def __init__(self):
      pass

    def Write(self,t):
      self.response.out.write(t)

    def Writeln(self,t):
      self.response.out.write(str(t)+"\n")

    def SCTCStats(self):

        query='select __key__ from Membership order by last'
        keys =  db.GqlQuery( query )
        mlist=[]
        rcount = ncount = 0
        non2012= non2011 = 0
        res2012= res2011 = 0

        for r in keys:
            e = db.get(r )     
            e.last = e.last.strip("*#")
            e.first = e.first.strip("*#")

            if(  e.year==2012): 
              if( re.search("clara",e.city , re.IGNORECASE) ):
                 res2012 = res2012 +1
              else:
                 non2012 = non2012 +1

            if( e.year>=2011):
              if( re.search("clara",e.city , re.IGNORECASE) ):
                 res2011 = res2011 +1
              else:
                 non2011 = non2011 +1



        self.Writeln("Santa Clara Tennis Club<br>")
        self.Writeln("2012: " + str(res2012)  + " residents/" + str(non2012) + " non-residents")
        self.Writeln("<br>")
#       self.Writeln("2011+: " + str(res2011)  + " residents/" + str(non2011) + " non-residents")

    def get(self,fac):


        if( fac == "stats"):
         self.SCTCStats()   
        elif( fac == "excel"):
         self.SCTCExcel()   
        else:
         self.SCTCDisplay()   

    def SCTCExcel(self):
        self.Writeln("Santa Clara Tennis Club<br>")

        query='select __key__ from Membership order by last'
        keys =  db.GqlQuery( query )
        mlist=[]

        for r in keys:
               e = db.get(r )     
               self.Writeln(e.last +", "+ e.first + ", " + str(e.year) + ", " + e.address + ", " + e.city + ", " + e.zip )
               self.Writeln(", " + e.rating + ", "+ e.email + "<br>")




    def SCTCDisplay(self):

        query='select __key__ from Membership order by last'
        keys =  db.GqlQuery( query )
        mlist=[]
        rcount = ncount = total =  0
        total = 0
        for r in keys:
               e = db.get(r )     

#              if( re.search("#",e.last , re.IGNORECASE) == None):  continue


               m=Member()
      
               e.last = e.last.strip("*#")
               e.first = e.first.strip("*#")


               if( re.search("taryn",e.first , re.IGNORECASE)):  e.rating="4.5"
               if( re.search("madsen",e.last , re.IGNORECASE)):  e.rating="4.5"
               if( re.search("montana",e.last , re.IGNORECASE)):  e.rating="4.5"
               if( re.search("oda",e.last , re.IGNORECASE)):  e.rating="4.0"
               if( re.search("tajima",e.last , re.IGNORECASE)):  e.rating="4.5"
               if( re.search("fiona",e.first , re.IGNORECASE)):  e.rating="4.0"

               if( re.search("dominto",e.last , re.IGNORECASE)):  e.last="Domingo"
               if( re.search("karri",e.first , re.IGNORECASE)):  e.first="Kaori"

               if( re.search("bean",e.last , re.IGNORECASE)):  e.rating="4.0"
               if( re.search("fiona",e.first , re.IGNORECASE)):  e.rating="4.0"


               if( re.search("bruno",e.first , re.IGNORECASE)):  e.rating="4.5"

               if( re.search("kay",e.first , re.IGNORECASE) and re.search("baik",e.last,re.IGNORECASE)): e.rating="4.0"
               if( re.search("jason",e.first , re.IGNORECASE) and re.search("lee",e.last,re.IGNORECASE)): e.rating="4.5"
               if( re.search("juli",e.first , re.IGNORECASE) and re.search("tachi",e.last,re.IGNORECASE)): e.rating="4.0"

               resident = "N"

               total =total + 1
               if( re.search("clara",e.city , re.IGNORECASE)): 
                   resident="Y"
                   if( e.year == 2012):  rcount = rcount +1
                   xcount= rcount
               else:
                   if( e.year == 2012):  ncount = ncount +1
                   xcount= ncount


               m.resident=resident
               m.first=e.first 
               m.last=e.last #+ "(" + str(xcount) + "/" + str(total) + ")"
               m.rating=e.rating
               m.email = e.email 
               m.year=e.year
               mlist.append(m)


        template_values = {
               'Member'     : mlist,
               'Residents'  : rcount,
               'NonResidents'  : ncount

        }

        path = os.path.join(os.path.dirname(__file__), 'display_sctc.html')
        self.response.out.write(template.render(path, template_values))





application = webapp.WSGIApplication(
                                     [('/(sctc)', Display),
                                     ('/(stats)', Display),
                                     ('/(excel)', Display),
                                     ('/()', Display)],
                                     debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":

#   print __file__
#   print __name__

    main()
